
#include "swordsman.h"
#include "towerinfo.h"
#include "gameplayscene.h"
#include "gamemanager.h"
#include "CCSkeletalSprite.h"
#include "bullet.h"
#include "enemy.h"

#define __super			Soldier

Swordsman::Swordsman() {

}

Swordsman::~Swordsman() {

}

void Swordsman::handleStateWalk( float ticks )
{
	if(!move(ticks)) {
		switch(state) {
		case UnitState::walk_to_flag:
			transformState(UnitState::stand);
			break;
		case UnitState::head_to_fight:
			transformState(UnitState::melee);
			
			if(target->target == this) {
				target->transformState(UnitState::melee);
			}
			break;
		default:break;
		}
	} else {
		if(state == UnitState::head_to_fight) {
			if(target) {
				Point pos = target->position;
				if(pos.x < position.x) {
					pos.x += 30.0f;
				} else {
					pos.x -= 30.0f;
				}
				moveTo(pos);
			} else {
				transformState(UnitState::stand);
			}
		}
	}
}

void Swordsman::handleStateStand( float ticks )
{
	target = findEnemy();
	if(target) {
		Point pos = target->position;
		if(pos.x < position.x) {
			pos.x += 30.0f;
		} else {
			pos.x -= 30.0f;
		}
		
		if(!target->target) {
			target->target = this;
			target->transformState(UnitState::head_to_fight);
		}
		
		moveTo(pos);
		transformState(UnitState::head_to_fight);
	} else {
		regroup();
	}
}

void Swordsman::handleStateMelee( float ticks )
{
	if(sprite->animationIsDone()) {
		transformState(UnitState::reload);
	}
}

Unit* Swordsman::findEnemy()
{
	Enemy* ret = nullptr;
	float minDistance = 9999.0f;

	for(Enemy* unit : gamePlayScene->enemies) {
		if(unit->position.x <= 0.0f ||
			unit->position.x >= GM->BASE_WIDTH ||
			unit->position.y <= 0.0f ||
			unit->position.y >= GM->BASE_HEIGHT ||
			fabs(unit->position.x - position.x) > attribute.range ||
			fabs(unit->position.y - position.y) > attribute.range) {
				continue;
		}

		float distance = position.getDistance(unit->targetPosition);
		if(distance < minDistance && distance < attribute.range) {
			ret = unit;
			minDistance = distance;
		}
	}

	return ret;
}

void Swordsman::attack()
{
	if(target) {
		Bullet* bullet = new Bullet();
		bullet->unitID = id;
		bullet->meleeDamage = attribute.meleeDamage;
		bullet->init();
		target->bullets.push_back(bullet);
	}
}

void Swordsman::handleEnterState()
{
	__super::handleEnterState();

	if((previousState == UnitState::reload || previousState == UnitState::melee) && state == UnitState::stand) {
		regroup();
	}
}